package com.uni.controller.admin;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.uni.base.RestResponse;
import com.uni.pojo.Address;
import com.uni.pojo.User;
import com.uni.service.UserService;
import com.uni.utils.PageUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.*;

@RestController
@RequestMapping("/admin/user")
public class UserAdminController {
    @Autowired
    UserService userService;

    @PostMapping("/query")
    public String toAdminUserByPage(@RequestBody(required = false) Map<String, String> paramMap) throws UnsupportedEncodingException {
        int pageNow = 1;
        if(paramMap!=null){
            for (String param : paramMap.keySet()) {
                paramMap.put(URLDecoder.decode(param, "utf-8"),
                        URLDecoder.decode(paramMap.get(param), "utf-8"));
            }
            pageNow = Integer.parseInt(paramMap.getOrDefault("pageNow", "1"));
        }
        // 获取请求的参数
        PageHelper.startPage(pageNow, 5);
        List<User> usersInfo = userService.getUserByMapPojos(paramMap);
        PageInfo pageInfo = PageUtil.setPageInfo(pageNow, 5, usersInfo);
        return RestResponse.ok(new HashMap<String, Object>(){{
            put("pageInfo", pageInfo);
        }}).toJSONString();
    }

    @PostMapping("/search")
    public String toAdminUserByPageBySome(@RequestBody Map<String, String> paramMap){
        int pageNow = Integer.parseInt(paramMap.getOrDefault("pageNow", "1"));
        PageHelper.startPage(pageNow, 5);
        List<User> usersInfo = userService.getUserByMapPojos(paramMap);
        PageInfo pageInfo = PageUtil.setPageInfo(pageNow, 5, usersInfo);
        return RestResponse.ok(new HashMap<String, Object>(){{
            put("usersInfo", usersInfo);
            put("pageInfo", pageInfo);
        }}).toJSONString();
    }

    @PostMapping("/add")
    public String addUser(User user, @RequestParam("rid") Integer rid, Address address){
        User result = userService.addUserWithRole(user, rid, address);
        return result == null ?
                RestResponse.fail("添加失败.").toJSONString()
                    : RestResponse.ok("添加成功!").toJSONString();
    }
    @PostMapping("/delete")
    public String deleteUser(@RequestBody Map<String, Object> map){
        List<Long> ids = (List<Long>) map.get("ids");
        int i = 0;
        if(!ids.isEmpty()){
            i = userService.removeUserByIds(ids);
        }
        // 删除用户+角色，正常情况下，操作数应为原先ID合计的两倍
        return i == ids.size() * 2 ? RestResponse.ok("删除成功!").toJSONString()
                : RestResponse.fail("删除失败.").toJSONString();
    }

}
